<template>
  <div class="app-container">
    <!-- 添加商品管理对话框 -->
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <ul class="flex">
        <li>
          <el-form-item label="商品分类" prop="productCategoryId">
            <el-select
              v-model="form.firstCategoryId"
              placeholder="请选择"
              @change="handleFirstCategoryChange"
              style="width: 30%; margin-right: 10px"
            >
              <el-option
                v-for="item in firstCategories"
                :key="item.categoryId"
                :label="item.categoryName"
                :value="item.categoryId"
              />
            </el-select>

            <el-select
              v-model="form.secondCategoryId"
              placeholder="请选择"
              @change="handleSecondCategoryChange"
              style="width: 30%; margin-right: 10px"
              :disabled="!form.firstCategoryId"
            >
              <el-option
                v-for="item in secondCategories"
                :key="item.categoryId"
                :label="item.categoryName"
                :value="item.categoryId"
              />
            </el-select>

            <el-select
              v-model="form.thirdCategoryId"
              placeholder="请选择"
              @change="handleThirdCategoryChange"
              style="width: 30%"
              :disabled="!form.secondCategoryId"
            >
              <el-option
                v-for="item in thirdCategories"
                :key="item.categoryId"
                :label="item.categoryName"
                :value="item.categoryId"
              />
            </el-select>
          </el-form-item>
        </li>
      </ul>
      <ul class="flex">
        <li>
          <el-form-item label="商品名" prop="productName">
            <el-input v-model="form.productName" placeholder="请输入商品名" />
          </el-form-item>
        </li>
        <li>
          <el-form-item label="商品简介" prop="productDescription">
            <el-input v-model="form.productDescription" placeholder="请输入商品简介" />
          </el-form-item>
        </li>
      </ul>
      <ul class="flex">
        <li>
          <el-form-item label="商品原价" prop="productPrice">
            <el-input v-model="form.productPrice" placeholder="请输入商品原价" />
          </el-form-item>
        </li>
        <li>
          <el-form-item label="商品售卖价" prop="productSaleprice">
            <el-input v-model="form.productSaleprice" placeholder="请输入商品售卖价" />
          </el-form-item>
        </li>
      </ul>
      <ul class="flex">
        <li>
          <el-form-item label="商品库存" prop="productStore">
            <el-input v-model="form.productStore" placeholder="请输入商品库存" />
          </el-form-item>
        </li>
        <li>
          <el-form-item label="商品小标签" prop="productTag">
            <el-input v-model="form.productTag" placeholder="请输入商品小标签" />
          </el-form-item>
        </li>
      </ul>
      <el-form-item label="商品上架状态" prop="productState">
        <el-radio-group v-model="form.productState">
          <el-radio :label="1">上架</el-radio>
          <el-radio :label="0">下架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <editor v-model="form.productContent" :min-height="400"/>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="cancel">返回</el-button>
      </el-form-item>

    </el-form>


    <!-- 图片上传弹窗 -->
    <el-dialog
      title="上传商品图片"
      :visible.sync="uploadDialogVisible"
      width="50%"
      :close-on-click-modal="false"
      :before-close="handleUploadClose">
      <el-upload
        class="upload-demo"
        :action="uploadUrl"
        :headers="headers"
        :data="{ productId: tempProductId }"
        :on-success="handleUploadSuccess"
        :before-upload="beforeUpload"
        :on-error="handleUploadError"
        :file-list="fileList"
        list-type="picture"
        multiple
        :limit="5">
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">请上传商品图片，支持jpg/png格式</div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleUploadClose">跳过上传</el-button>
        <el-button type="primary" @click="confirmUpload">完成上传</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
import { addProduct, getProduct, updateProduct } from "@/api/system/product";
import { getToken } from '@/utils/auth'
import { listCategory, getCategory } from "@/api/system/category";

export default {
  name: "add",

  data() {
    return {
      uploadDialogVisible: false,
      fileList: [],
      tempProductId: null,
      uploadUrl: process.env.VUE_APP_BASE_API + "/system/product/upload",
      headers: {
        Authorization: 'Bearer ' + getToken()
      },

      allCategories: [],     // 全部分类
      firstCategories: [],   // 一级分类
      secondCategories: [],  // 二级分类
      thirdCategories: [],   // 三级分类

      isInitializing: false,

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品管理表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        productDescription: null,
        productPrice: null,
        productSaleprice: null,
        productStore: null,
        productTag: null,
        productState: null,
        productContent: null,
        productCategoryId: null,
        productHref: null,
        productPhoto: null,
        productAddtime: null
      },
      // 表单参数
      form: {
        firstCategoryId: null,
        secondCategoryId: null,
        thirdCategoryId: null,
      },
      // 表单校验
      rules: {
      }
    }
  },
  created() {
    this.getFirstCategories(); // 初始化一级分类

    // 如果是编辑模式（有id参数），则加载商品数据
    if (this.$route.query.id) {
      this.loadProductData(this.$route.query.id);
    }


  },
  methods: {
    async loadProductData(id) {
      try {
        this.isInitializing = true; // 标记为初始化阶段

        const res = await getProduct(id);

        // 手动反转义富文本内容
        const rawContent = this.htmlDecode(res.data.productContent);
        this.form = {
          ...res.data,
          productContent: rawContent // 覆盖为反转义后的内容
        };

        this.form = res.data; // 回显数据

        // 获取商品对应的分类ID(三级分类)
        const third = this.form.productCategoryId;

        // 获取当前商品分类的所属二级分类
        const second = await getCategory(third);

        //获取当前商品分类的所属一级分类
        const first = await getCategory(second.data.categoryParentId);

        this.form.firstCategoryId = first.data.categoryParentId;
        this.form.secondCategoryId = second.data.categoryParentId;
        this.form.thirdCategoryId = third;

        //刷新分类下拉框
        await this.getFirstCategories();
        await this.handleFirstCategoryChange(this.form.firstCategoryId);
        await this.handleSecondCategoryChange(this.form.secondCategoryId);
        await this.handleThirdCategoryChange(third);


      } catch (error) {
        this.$modal.msgError("获取商品数据失败");
      } finally {
        this.isInitializing = false; // 初始化完成
      }
    },
    // 新增HTML反转义方法
    htmlDecode(input) {
      const doc = new DOMParser().parseFromString(input, "text/html");
      console.log(doc);
      return doc.documentElement.textContent;
    },
    /** 查询商品管理列表 */
    getList() {
      this.loading = true
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    /** 查询分类管理列表 */
    // 获取一级分类
    async getFirstCategories() {
      const res = await listCategory({ categoryParentId: 0}); // 获取所有一级分类
      this.firstCategories = res.rows || res.data || [];
    },

    // 一级分类变化时，加载二级分类
    async handleFirstCategoryChange(firstId) {
      if (!this.isInitializing) {
        this.form.secondCategoryId = null;
        this.form.thirdCategoryId = null;
      }
      if (!firstId) return;
      const res = await listCategory({ categoryParentId: firstId }); // 获取二级分类
      this.secondCategories = res.rows || res.data || [];
    },

    // 二级分类变化时，加载三级分类
    async handleSecondCategoryChange(secondId) {
      if (!this.isInitializing) {
        this.form.thirdCategoryId = null;
      }
      if (!secondId) return;
      const res = await listCategory({ categoryParentId: secondId }); // 获取三级分类
      this.thirdCategories = res.rows || res.data || [];
    },

    // 三级分类变化时
    async handleThirdCategoryChange(thirdId) {
      if (!this.isInitializing) {
        this.form.thirdCategoryId = thirdId;
      }
      if (!thirdId) return;
      const res = await listCategory({ categoryParentId: thirdId }); // 获取三级分类
      this.thirdCategories = res.rows || res.data || [];
    },

    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.form.productCategoryId = this.form.thirdCategoryId;
          try {
            let res;
            if (this.$route.query.id) {
              // 编辑模式
              res = await updateProduct(this.form);
              this.$modal.msgSuccess("商品信息修改成功");
            } else {
              // 新增模式
              res = await addProduct(this.form);
              this.$modal.msgSuccess("商品添加成功");
            }
            this.tempProductId = res.data || this.form.productId;
            this.uploadDialogVisible = true;
          } catch (error) {
            this.$modal.msgError("操作失败");
          }
        }
      });
    },

    handleUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.$message.success('图片上传成功');
        // 更新当前商品的图片信息
        if (response.imgUrl) {
          this.form.productPhoto = response.imgUrl;
        }
      }
    },

    handleUploadError(err) {
      this.$message.error('上传失败: ' + err.message);
    },

    beforeUpload(file) {
      const isImage = file.type.includes('image/');
      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }
      return true;
    },

    handleUploadClose() {
      this.uploadDialogVisible = false;
    },

    confirmUpload() {
      this.uploadDialogVisible = false;
      this.$modal.msgSuccess("商品图片上传完成");
      // 返回商品管理页并刷新数据
      this.$router.push({
        path: "/managementModules/product",
        query: { refresh: true }  // 添加刷新标记
      });
    },

    cancel() {
      this.$router.go(-1);
    }
  }
}
</script>

<style scoped>
  .flex{
    padding: 0;
    display: flex;
  }
  .flex li{
    list-style: none;
    width: 50%;
  }
</style>
